package com.conversationboard.filter.compression;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Left here for interest. Easier to go to server.xml and on the Connector node add the attribute: compression="force", which has
 * much the same effect. This approach is a little strange in that sometimes it takes ages to return to the client... Something
 * clearly isn't right about it, but the site isn't currently using this code. * 
 * 
 * @author Keith Watson
 *
 */

public class CompressionFilter implements Filter {

    private int minimumToCompress;


    public void init(FilterConfig filterConfig) {
        this.minimumToCompress = Integer.parseInt(filterConfig.getInitParameter("minimumToCompress"));
    }


    public void destroy() {
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
            chain.doFilter(request, response);
            return;
        }

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        if (minimumToCompress == 0) {
            chain.doFilter(request, response);
            return;
        }

        boolean browserSupportsCompression = false;
        
        if (request instanceof HttpServletRequest) {

            Enumeration encodings = httpRequest.getHeaders("Accept-Encoding");

            while (encodings.hasMoreElements()) {
                String encoding = (String) encodings.nextElement();

                if (encoding.contains("gzip")) {
                    browserSupportsCompression = true;
                    break;
                }
            }

        }

        if (!browserSupportsCompression) {
            chain.doFilter(request, response);
            return;
        }

        CompressionServletResponseWrapper wrappedResponse = new CompressionServletResponseWrapper((HttpServletResponse) response);
        wrappedResponse.setMinimumToCompress(minimumToCompress);

        try {
            chain.doFilter(request, wrappedResponse);
        } finally {
            wrappedResponse.finishResponse();
        }

    }

}
